const api = require('../../../utils/api.js');

Page({
  data: {
    loading: true,
    currentDate: '',
    currentMeal: 'breakfast',
    plan: {
      dailyCalories: 0,
      currentCalories: 0,
      protein: 0,
      currentProtein: 0,
      carbs: 0,
      currentCarbs: 0,
      fat: 0,
      currentFat: 0,
      suggestions: [],
      recommendedIngredients: [],
      meals: {
        breakfast: [],
        lunch: [],
        dinner: [],
        snacks: []
      }
    }
  },

  onLoad() {
    this.setCurrentDate();
    this.getNutritionPlan();
  },

  // 设置当前日期
  setCurrentDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    this.setData({
      currentDate: `${year}-${month}-${day}`
    });
  },

  // 获取营养方案
  getNutritionPlan() {
    this.setData({ loading: true });

    api.getNutritionPlan().then(res => {
      if (res.code === 200 && res.data) {
        // 处理返回的数据
        const plan = this.processNutritionPlan(res.data);
        this.setData({
          plan,
          loading: false
        });
      } else {
        this.setData({ loading: false });
        wx.showToast({
          title: '获取方案失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('获取营养方案失败:', err);
      this.setData({ loading: false });
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });

      // 使用模拟数据
      this.setMockData();
    });
  },

  // 处理营养方案数据
  processNutritionPlan(data) {
    return {
      dailyCalories: data.dailyCalories || 2000,
      currentCalories: data.currentCalories || 0,
      protein: data.protein || 60,
      currentProtein: data.currentProtein || 0,
      carbs: data.carbs || 250,
      currentCarbs: data.currentCarbs || 0,
      fat: data.fat || 67,
      currentFat: data.currentFat || 0,
      suggestions: data.suggestions || [],
      recommendedIngredients: data.recommendedIngredients || [],
      meals: data.meals || {
        breakfast: [],
        lunch: [],
        dinner: [],
        snacks: []
      }
    };
  },

  // 设置模拟数据
  setMockData() {
    const mockPlan = {
      dailyCalories: 2000,
      currentCalories: 850,
      protein: 60,
      currentProtein: 25,
      carbs: 250,
      currentCarbs: 100,
      fat: 67,
      currentFat: 30,
      suggestions: [
        {
          id: 1,
          icon: '/images/suggestions/water.png',
          title: '多喝水',
          description: '建议每天饮水2000ml，可以帮助身体代谢，保持水分平衡。'
        },
        {
          id: 2,
          icon: '/images/suggestions/vegetables.png',
          title: '增加蔬菜摄入',
          description: '每餐保证有不同颜色的蔬菜，提供多样化的维生素和矿物质。'
        }
      ],
      recommendedIngredients: [
        {
          id: 1,
          name: '鸡胸肉',
          image: '/images/ingredients/chicken-breast.jpg',
          nutrition: '高蛋白低脂肪'
        },
        {
          id: 2,
          name: '三文鱼',
          image: '/images/ingredients/salmon.jpg',
          nutrition: '富含omega-3'
        },
        {
          id: 3,
          name: '藜麦',
          image: '/images/ingredients/quinoa.jpg',
          nutrition: '优质碳水'
        }
      ],
      meals: {
        breakfast: [
          {
            id: 1,
            name: '全麦吐司配煎蛋',
            image: '/images/meals/toast-egg.jpg',
            description: '优质碳水配合高蛋白，为一天提供充足能量',
            calories: 300,
            protein: 15
          }
        ],
        lunch: [
          {
            id: 2,
            name: '鸡胸肉沙拉',
            image: '/images/meals/chicken-salad.jpg',
            description: '低脂高蛋白，搭配新鲜时蔬',
            calories: 400,
            protein: 30
          }
        ],
        dinner: [
          {
            id: 3,
            name: '三文鱼配西兰花',
            image: '/images/meals/salmon-broccoli.jpg',
            description: '优质蛋白搭配绿叶蔬菜',
            calories: 450,
            protein: 28
          }
        ],
        snacks: [
          {
            id: 4,
            name: '希腊酸奶配蓝莓',
            image: '/images/meals/yogurt-blueberry.jpg',
            description: '健康美味的加餐选择',
            calories: 150,
            protein: 12
          }
        ]
      }
    };

    this.setData({ plan: mockPlan });
  },

  // 切换餐次
  switchMeal(e) {
    const meal = e.currentTarget.dataset.meal;
    this.setData({ currentMeal: meal });
  },

  // 查看餐品详情
  viewMealDetail(e) {
    const mealId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/nutrition/meal/index?id=${mealId}`
    });
  },

  // 调整方案
  adjustPlan() {
    wx.navigateTo({
      url: '/pages/nutrition/assessment/index'
    });
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '我的专属营养方案',
      path: '/pages/nutrition/plan/index',
      imageUrl: '/images/share-nutrition-plan.png'
    };
  }
}); 